import logging
import uuid

from django.db import DatabaseError
from django.views import View
from django.http import JsonResponse, HttpResponse
import json
import re

from aijia_mall import settings
from apps.users.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login, logout
from utils.views import LoginRequiredJSONMin
from libs.qiniu.qiniu_storage import storage
from utils.param_checking import image_file


class UserView(View):

    def post(self, request):
        """
        实现用户注册功能
        :param request:
        :return:
        """
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')

        if not all([mobile, phonecode, password]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数'})
        if not re.match('1[3-9]\d', mobile):
            return JsonResponse({'errno': 400, 'errmsg': '格式错误'})
        if not re.match('[a-zA-Z0-9]{8,20}', password):
            return JsonResponse({'errno': 400, 'errmsg': '格式错误'})

        try:
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile,
                                            password=password)
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '注册不成功'})
        return JsonResponse({'errno': 0, 'errmsg': 'ok'})


class LoginView(View):

    def get(self, request):
        """
        实现用户登陆和退出功能
        :param request:
        :return:
        """

        # 1、判断用户是否登录，需要获取user
        user = request.user
        # 2、对user进行认证
        if not user.is_authenticated:
            return JsonResponse({"errno": 4101, "errmsg": "用户未登录"})

        data = {
            "user_id": user.id,
            "name": user.username
        }
        return JsonResponse({"errno": 0, "errmsg": "已登录", "data": data})

    def post(self, request):
        dict_data = json.loads(request.body.decode())
        mobile = dict_data.get('mobile')
        password = dict_data.get('password')

        # 校验参数
        # 判断参数是否齐全
        if not all([mobile, password]):
            return JsonResponse({"errno": 400, "errmsg": "参数不全"})

        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({"errno": 400, "errmsg": "请输入正确的手机号码"})

        # 认证登录用户
        user = authenticate(username=mobile, password=password)
        if user is None:
            return JsonResponse({"errno": 400, "errmsg": "请输入正确的手机号码"})

        # 实现状态保持
        login(request, user)

        return JsonResponse({"errno": 0, "errmsg": "登录成功"})

    def delete(self, request):

        logout(request)

        return JsonResponse({"errno": 0, "errmsg": "退出成功"})


class UserInfoView(LoginRequiredJSONMin, View):

    def get(self, request):
        """
        个人中心数据获取
        :param request:
        :return:
        """
        user = request.user
        user_info = {
            "avatar": None,  # 后续需要进一步修改
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id
        }
        return JsonResponse({'errmsg': 'ok', 'errno': 0, 'data': user_info})


class ModifyNameView(LoginRequiredJSONMin, View):

    def put(self, request):
        """
        修改用户名功能的实现
        :param request:
        :return:
        """
        data = json.loads(request.body.decode())
        name = data.get('name')
        user = request.user
        user.username = name
        user.save()
        return JsonResponse({'errno': 0, 'errmsg': '修改成功'})


# 头像上传
from qiniu import Auth,put_data
access_key = 'PCulTwc2C7DKq5ykfYrUd5JWEOgLzmo-bfDWqRnE'
secret_key = 'g2ZtNzwC1FQShHRulm4i4K9uazOJRuYc5RWdElnf'
bucket_name = 'aijiaoy'
secure_url = 'http://qn41u710y.hn-bkt.clouddn.com/'


class UploadView(LoginRequiredJSONMin, View):
    """
    上传头像
    """
    def post(self, request):
        user = request.user

        # 1、接收参数
        avatar = request.FILES.get("avatar")

        key = 'image_%s' % avatar
        q = Auth(access_key, secret_key)
        token = q.upload_token(bucket_name, key, 3600)
        print(token)

        if not avatar:
            return JsonResponse({"errno": 400, "errmsg": "参数错误"})

        if not image_file(avatar):
            return JsonResponse({"errno": 400, "errmsg": "参数错误"})

        try:
            request.user.avatar = key
            request.user.save()
        except DatabaseError as e:
            print(e)
            return JsonResponse({"errno": 400, "errmsg": "图片保存失败"})
        data = {
            "avatar_url": secure_url + key
        }

        res = put_data(token, key, avatar)
        print(res)
        return JsonResponse({"errno": 0, "errmsg": "OK", "data": data})


# 实名认证
class AuthUserView(LoginRequiredJSONMin,View):
    '''实名认证'''
    def post(self,request):
        data = json.loads(request.body.decode())
        real_name = data.get('real_name')
        id_card = data.get('id_card')
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 400, 'errmsg': '参数错误'})

        if not re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                        id_card):
            return JsonResponse({
                "errno": "4103",
                "errmsg": "身份证格式不正确"
            })

        user = request.user
        try:
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'errno': 400, 'errmsg': '数据保存失败'})
        else:
            return JsonResponse({'errno': 0, 'errmsg': '认证信息保存成功'})

    def get(self, request):
        real_name = request.user.real_name
        id_card = request.user.id_card
        user_data = {
            'real_name': real_name,
            'id_card': id_card
            }
        return JsonResponse({'errno': 0, 'errmsg': '认证信息查询成功', 'data': user_data})